/* $RCSFile: UpdateCrmEntity.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmServerManager/UpdateCrmEntity.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:52  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.UI;
using AddonNice.Settings;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Core;
using AddonNice.CRMWrapper;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Path2     =   AddonNice.Settings.Path;

namespace AddonNice.PageModules.CrmServerManager
{
	/// <summary>
	/// Add/Remove modules, assign modules to portals
	/// </summary>
	public partial class UpdateCrmEntity : EditItemPage
	{
        CrmDB CrmManDB                  =   new CrmDB();

        int CrmServerId
        {
            get
            {
                if ( Request.QueryString["crmserverid"] != null )
                    return int.Parse(Request.QueryString["crmserverid"]);
                return -1;
            }
        }

        int CrmEntityId
        {
            get
            {
                if ( Request.QueryString["crmentityid"] != null )
                    return int.Parse(Request.QueryString["crmentityid"]);
                return -1;
            }
        }

        private void Page_Load(object sender, System.EventArgs e)
		{
			if (InstallTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UpdateCrmEntity Page_Load BEG IsPostBack: {0}",IsPostBack),InstallTraceSwitch.Sw.Info);
            PageProgressArea                            =   RadProgressArea1;
            InitProgress();
			// If this is the first visit to the page, bind the definition data 
			if ( !IsPostBack )
			{
                SqlDataReader dr                        =   null;
                try
                {
                    if ( CrmServerId != -1 )
                    {
                        LblCrmServerId.Text             =   CrmServerId.ToString();
                        DBCrmServer srvObj              =   CrmManDB.GetCrmServerObj(CrmServerId);
                        LblCrmServerName.Text           =   srvObj.FriendlyName;
                        LblCrmServerOrganization.Text   =   srvObj.Organization;
                    }
                    if ( CrmEntityId != -1 )
                    {
                        PnlEntity.Visible               =   true;
                        LblEntityId.Text                =   CrmEntityId.ToString();
                        DBCrmEntity entObj              =   CrmManDB.GetCrmEntityObj(CrmEntityId);
                        LblEntityName.Text              =   entObj.SchemaName;
                        LblEntityVersion.Text           =   entObj.EntityVersion;

                        dr                              =   CrmManDB.GetCrmServerEntity(CrmServerId,CrmEntityId);
                        if ( dr.Read() )
                        {
                            LblInstalledVersion.Text    =   (string)dr["InstalledVersion"];
                            LblInstalledDate.Text       =   ((DateTime)dr["InstallDate"]).ToShortDateString();
                        }
                    }
                }
                catch (Exception ex )
                {
			        if (InstallTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]UpdateCrmEntity Page_Load ex: {0}",ex),InstallTraceSwitch.Sw.Info);
                    throw;
                }
                finally
                {
                    if ( dr != null )
                        dr.Close();
                }
			}
			if (InstallTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]UpdateCrmEntity Page_Load END.",InstallTraceSwitch.Sw.Info);
		}

		/// <summary>
		/// Set the module guids with free access to this page
		/// </summary>
		protected override ArrayList AllowedModules
		{
			get
			{
				ArrayList al = new ArrayList();
				al.Add ("7353B8ED-CDD2-46a5-8BAD-91E29EEAB42A"); // CrmServerManager
				return al;
			}
		}

		/// <summary>
		/// OnUpdate installs or refresh a CrmServer, it installs Custom entities not already installed
        /// beware it doesn't install the portal as we don't know if already selected
		/// </summary>
        void UpdateCrmEntity_Update(object sender, ADNPageEventArgs e)
		{
			if (InstallTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UpdateCrmEntity UpdateCrmEntity_Update BEG CrmServerId: {0}, CrmEntityId: {1}",CrmServerId,CrmEntityId),InstallTraceSwitch.Sw.Info);
            if ( ( CrmServerId == -1 ) || ( CrmEntityId == -1 ))
            {
                e.Cancel                    =   true;
                return;
            }
            CrmInstaller installer          =   null;
			try
			{
                installCount                =   0;
                totalSteps                  =   100;
                // build list of forbidden packages
                List<string> ForbiddenPackages   =   new List<string>();
			    if (InstallTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UpdateCrmEntity UpdateCrmEntity_Update ForbiddenPackages: {0}",ForbiddenPackages.Count),InstallTraceSwitch.Sw.Info);
                StartProgress();
                installer                   =   new CrmInstaller(portalSettings.DefaultCrmBackupPath,ForbiddenPackages,
                                                        delegate(string msg, int countInc)
                                                        { 
                                                            installCount        +=  countInc;
                                                            SetUpdateProgress(msg,installCount);
                                                        },
                                                        delegate(int newTot,int newVal)
                                                        { 
                                                            installCount        =   newVal;
                                                            SetTotalStepsProgress(newTot,newVal);
                                                        });
                DBCrmEntity entObj          =   CrmManDB.GetCrmEntityObj(CrmEntityId);
                installer.UpdateEntity(entObj,CrmServerId);
	            if (InstallTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UpdateCrmEntity UpdateCrmEntity_Update installer.nbInstalled: {0}.", installer.nbInstalled),InstallTraceSwitch.Sw.Info);
                if (installer.nbInstalled > 0)
                {
				    string fmt          =   LocalizeHelper.Localize("UPDATECRMENTITY_INSTALLSUCCESS", "Success updating Entity {0} in Crm Server {1}.");
                    lblErrorDetail.Text =   string.Format(fmt, LblEntityName.Text,LblCrmServerName.Text);
                }
                else
                {
				    string fmt          =   LocalizeHelper.Localize("UPDATECRMENTITY_NOTHING2UPDATE", "Entity {0} in Crm Server {1}: nothing new to update.");
                    lblErrorDetail.Text =   string.Format(fmt, LblEntityName.Text,LblCrmServerName.Text);
                }
			}
			catch (CrmInstallException cex)
			{
				if (InstallTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]UpdateCrmEntity UpdateCrmEntity_Update ex : {0}", cex),InstallTraceSwitch.Sw.Info);
				string fmt              =   LocalizeHelper.Localize("UPDATECRMENTITY_UPDATEERR", "An error occurred updating crm Server '{0}'.<br />{1}");
                if (( installer != null ) && ( installer.srvObj != null ) )
				     lblErrorDetail.Text     =  string.Format(fmt,installer.srvObj.FriendlyName,installer.lastError);
				else lblErrorDetail.Text     =  string.Format(fmt,CrmServerId,installer.lastError);
				lblErrorDetail.Visible  =   true;
                e.Cancel                =   true;
                return;
			}
			catch (Exception ex)
			{
				if (InstallTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]UpdateCrmEntity UpdateCrmEntity_Update ex : {0}", ex),InstallTraceSwitch.Sw.Info);
				string fmt              =   LocalizeHelper.Localize("INSTALCRMORG_INSTALLING", "An error occurred installing crm Server '{0}'.");
                if (( installer != null ) && ( installer.srvObj != null ) )
				     lblErrorDetail.Text     =  string.Format(fmt,installer.srvObj.FriendlyName);
				else lblErrorDetail.Text     =  string.Format(fmt,CrmServerId);
				lblErrorDetail.Visible  =   true;
                e.Cancel                =   true;
                return;
			}
            finally
            {
                EndProgress();
            }
		    if (InstallTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UpdateCrmEntity UpdateCrmEntity_Update END CrmServerId: {0}.", CrmServerId),InstallTraceSwitch.Sw.Info);
		}
 

		#region Std overrides

        override protected void OnPreInit(EventArgs e)
        {
	        if (InstallTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]UpdateCrmEntity OnPreInit BEG.",InstallTraceSwitch.Sw.Info);
            MasterPage m                        =   Master; // to have buttons instanciated, little pb .net
			//string strLoc			            =	Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            base.OnPreInit(e);
	        if (InstallTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]UpdateCrmEntity OnPreInit END.",InstallTraceSwitch.Sw.Info);
        }

		override protected void OnInit(EventArgs e)
		{
	        if (InstallTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]UpdateCrmEntity OnInit BEG.",InstallTraceSwitch.Sw.Info);
			InitializeComponent();	
            if ( CrmEntityId == -1 )
            {
                updateButton.Visible            =   false;
                updateButton2.Visible           =   false;
                saveAndCloseButton.Visible      =   false;
                saveAndCloseButton2.Visible     =   false;
            }
			base.OnInit(e);
	        if (InstallTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]UpdateCrmEntity PreInit END.",InstallTraceSwitch.Sw.Info);
		}

		private void InitializeComponent() 
		{    
			Load						+=	new System.EventHandler(Page_Load);
            Update                      +=  new PageEventHandler(UpdateCrmEntity_Update);
 		}


		protected override PlaceHolder placeHolderForButtons
		{
			get
			{ return PlaceHolderButtons; }
			set { }
		}

        protected override PlaceHolder placeHolderForButtons2
		{
			get
			{ return PlaceHolderButtons2; }
			set { }
		}

		#endregion Std overrides

    }
}

